<template>
    <a-modal :visible="visible"  @cancel="closeModal" title-align="start" @ok="handleOk">

        <template #title>
            {{ modalType === 'add' ? '新增菜单' : '编辑菜单' }}
        </template>
        <div>
   
            <XForm :config="formConfig" ref="xFormRef" style="width: 100%">
                <template #parentId="scoped">
               
                    <a-tree-select
                        :data="(TreeSelectData as any)"
                        :fieldNames="{
                            key: 'menuId',
                            title: 'menuName',
                            children: 'children',
                            
                        }"
                       allow-clear
                        v-model="scoped.modelValue"
                        placeholder="请选择父级菜单"
                   
                    ></a-tree-select>
                </template>
            </XForm>
        </div>
    </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, defineProps,defineEmits,watch, computed } from 'vue'
import type { PropType } from 'vue'
import XForm, { useFormHook } from '@/components/common/x-form/index.ts'
import type { FormPropsType } from '@/components/common/x-form/index.ts'
import { assign, cloneDeep,merge,mergeWith} from 'lodash'

let emits=defineEmits(["update:visible","submit"])
let props = defineProps({
  visible: {
        type: Boolean,
        default: false
    },
    modalType: {
        type: String as PropType<'add' | 'edit'>,
        default: 'add'
    },
    menuData: {
        type: Object as PropType<UserType.MenuInfo>,
        default: () => {}
    },
    allMenuData: {
        type: Array as PropType<UserType.MenuInfo[]>,
        default: () => []
    }
})

//格式化符合当前tree结构的数据
let TreeSelectData=computed<Array<UserType.MenuInfo&{disabled:boolean}>>(()=>{
  return formatMenuData(cloneDeep(props.allMenuData))
})

//递归对tree结构的数据进行格式化
function formatMenuData(data: Array<UserType.MenuInfo>) {
    return data.map((item: UserType.MenuInfo) => {
      if(item.children&&item.children.length>0){
        item.children=formatMenuData(item.children) 
      }
      return {
        ...item,
        disabled:(Number(item.type)==1||item.menuId==(props.menuData as UserType.MenuInfo).menuId)?true:false
    }

    })
}


const xFormRef = ref()

const formConfig = ref<FormPropsType>({
    autoLabelWidth: true,
    items: {
      parentId: {
            type: 'slot',
            config: {
                label: '父级菜单',
                style: {},
                feedback:true
            },
            slotFormConfig: {
                modelValue: (props.menuData as UserType.MenuInfo)?.parentId || '',
                options: []
            }
        },
        menuName: {
            type: 'input',
            config: {
                label: '菜单名称',
                rules: [{ required: true, message: 'menuName is required' }],
                style: {},
                feedback:true
            },
            slotFormConfig: {
                modelValue:  (props.menuData as UserType.MenuInfo)?.menuName || ''
            }
        },
        type: {
            type: 'radioGroup',
            config: {
                label: '菜单类型',
                rules: [{ required: true, message: 'type is required' }],
                style: {},
                feedback:true,
                disabled:computed(()=>{
                  if(props.modalType=='edit'&&(props.menuData as UserType.MenuInfo)?.children?.length>0){
                    return true
                  }else{
                    return false 
                  }
                })
            },
            slotFormConfig: {
                modelValue: (props.menuData as UserType.MenuInfo)?.type || 0,
                options: [
                    { label: '菜单', value: 0 },
                    { label: '页面', value: 1 }
                ]
            }
        },
        routePath: {
            type: 'input',
            config: {
                label: '菜单页面地址',
                feedback:true,
                rules:computed(()=>{
                 if(formConfig.value.items.type.slotFormConfig.modelValue==0){
                   return []
                 }else{
                   return [{ required: true, message: 'routePath is required' }]
                 }
                }),
                style: {}
            },
            slotFormConfig: {
                modelValue:  (props.menuData as UserType.MenuInfo)?.menuName || ''
            }
        },
        level: {
            type: "inputNumber",
            config: {
                label: '菜单等级顺序',
                feedback:true,
                rules:[{ required: true, message: 'level is required' }],
                style: {}
            },
            slotFormConfig: {
                modelValue:  (props.menuData as UserType.MenuInfo)?.level || ''
            }
        },
        // icon: {
        //     type: "input",
        //     config: {
        //         label: '菜单图标',
        //         feedback:true,
        //         style: {}
        //     },
        //     slotFormConfig: {
        //         modelValue:  (props.menuData as UserType.MenuInfo)?.icon || ''
        //     }
        // },
        isForbidden: {
            type: 'switch',
            config: {
                label: '是否禁用',
                feedback:true,
                // rules: [{ required: true, message: 'type is required' }],

                style: {}
            },
            slotFormConfig: {
              checkedValue:1,
               uncheckedValue:0,
                modelValue: (props.menuData as UserType.MenuInfo)?.isForbidden || 0
            }
        }
    }
})

let [formData,setFormItemValue] = useFormHook(formConfig)
watch(()=>props.menuData,()=>{
  setFormItemValue(Object.keys(formConfig.value.items).map(keyName=>{
    return {
      key:keyName,
      value:(props.menuData as any)[keyName]
    }
  }))
})


function handleOk(){
    xFormRef.value.FormRef.validate().then((res:any)=>{
        if(!res){
          emits("update:visible",false)
          emits("submit",assign(cloneDeep(props.menuData),cloneDeep(formData.value)),props.modalType)
        }
    })
}

function closeModal() {
    emits("update:visible",false) 
 
}
</script>
<style scoped lang="scss"></style>
